//
// Created by benxb on 2022/2/20.
//

#include <common/config.h>
#include <common/logger.h>

namespace benxdb {

std::string GlobalConfig::data_dir{};

std::string GlobalConfig::data_file_name{};

std::string GlobalConfig::meta_file_name{};
std::string GlobalConfig::delete_bitmap_file_name{};
std::string GlobalConfig::data_desc_file_name{};
std::string GlobalConfig::log_file_name{};
CompressStrategy GlobalConfig::compress_strategy{};
std::shared_ptr<INIReader> GlobalConfig::reader_{};

std::string GlobalConfig::DatasetDir(const std::string &dataset_name) {
//    return data_dir + dataset_name + "/";
    return reader_->Get("db", "data_dir", ".") + dataset_name + "/";
}

std::string GlobalConfig::DataFilePath(const std::string &dataset_name) {
    return DatasetDir(dataset_name) + data_file_name;
}

std::string GlobalConfig::MetaFilePath(const std::string &dataset_name) {
    return DatasetDir(dataset_name) + meta_file_name;
}

std::string GlobalConfig::DeleteMapFile(const std::string &dataset_name) {
    return DatasetDir(dataset_name) + delete_bitmap_file_name;
}

std::string GlobalConfig::LogFilePath(const std::string &dataset_name) {
    return DatasetDir(dataset_name) + log_file_name;
}

std::string GlobalConfig::DescFilePath(const std::string &dataset_name) {
    return DatasetDir(dataset_name) + data_desc_file_name;
}

void GlobalConfig::Init(const std::string &ini_file) {
    LOG_INFO("Loading database config.");
    reader_ = std::make_shared<INIReader>(ini_file);

    if (reader_->ParseError() != 0) {
        LOG_DEBUG("Can't load ini config.");
        return;
    }
    data_dir = reader_->Get("db", "data_dir", ".");
    data_file_name = reader_->Get("db", "data_file_name", "data");
    meta_file_name = reader_->Get("db", "meta_file_name", "meta");
    delete_bitmap_file_name = reader_->Get("db", "delete_bitmap_file_name", "delmap");
    log_file_name = reader_->Get("db", "log_file_name", "memlog");
    data_desc_file_name = reader_->Get("db", "data_desc_file_name", "desc");
    std::string compress_mode_str = reader_->Get("db", "compress_strategy", "NO_COMPRESS");

    if (compress_mode_str == "DELTA") {
        compress_strategy = DELTA;
    } else if (compress_mode_str == "LZ4") {
        compress_strategy = LZ4;
    } else if (compress_mode_str == "ZLIB") {
        compress_strategy = ZLIB;
    } else {
        compress_strategy = NO_COMPRESS;
    }
    LOG_DEBUG("data_dir: %s", GlobalConfig::data_dir.c_str());
}

}